package service

import (
	"errors"
	"fmt"
	"golang.org/x/crypto/bcrypt"
	databases "house/database"
	"house/models"
	"house/utils"
)

// 获取到
func getRedisCode(key string) (string, error) {
	exist, err := databases.RedisCLi.Exists(key).Result()
	if err != nil {
		return "", err
	}

	if exist == 0 {
		return "", errors.New("请重新获取验证码")
	}

	val := databases.RedisCLi.Get(key).Val()

	fmt.Println("key", val)

	return val, nil
}

func Login(account, pwd, code string) (string, error) {
	fmt.Println(account, pwd, code, "================================================================")

	userInfo, err := models.GetUserByUsername(account)
	if err != nil {
		return "", err
	}

	if pwd != "" {
		if userInfo == nil {
			return "", fmt.Errorf("初次登录请使用验证码登录")
		}

		token, err := utils.CreateToken(userInfo.Id)
		if err != nil {
			return "", err
		}

		err = bcrypt.CompareHashAndPassword([]byte(userInfo.Password), []byte(pwd))
		if err != nil {
			return "", fmt.Errorf("密码不正确")
		}

		return token, nil
	}

	if code == "" {
		return "", fmt.Errorf("验证码错误")
	}

	codeRedis, err := getRedisCode(account)
	if err != nil {
		return "", err
	}

	if code != codeRedis {
		return "", fmt.Errorf("验证码错误")
	}

	fmt.Println("********userInfo")
	fmt.Println(userInfo)
	if userInfo == nil {
		userInfo, err = models.CreateUser(&models.User{
			Account: account,
		})
		fmt.Println(userInfo)
		if err != nil {
			return "", fmt.Errorf("用户创建失败：%v", err)
		}
	}

	token, err := utils.CreateToken(userInfo.Id)
	if err != nil {
		return "", err
	}

	return token, nil
}
